

from django import http
from django.shortcuts import render
from django.views import View
from redis import StrictRedis

from apps.verifications.constant import SMS_CODE_EXPIRE_TIME, YUNTONGXUN_EXPIRE_TIME
from libs.yuntongxun.sms import CCP
from utils.response_code import RETCODE
import logging
logger = logging.getLogger('django')


class ImageCodeView(View):

    def get(self, request, uuid):

        from libs.captcha.captcha import captcha
        text,image = captcha.generate_captcha()
        from django_redis import get_redis_connection
        redis_coon=get_redis_connection('code')

        redis_coon.setex('img_%s' % uuid, 120, text)

        return http.HttpResponse(image, content_type='image/jpeg')

class SMSCodeView(View):

    def get(self, request, mobile):

        params = request.GET
        uuid =params.get('image_code_id')
        text_client=params.get('image_code')

        from django_redis import get_redis_connection


        try:
            redis_coon = get_redis_connection('code')
            text_server = redis_coon.get('img_%s' % uuid)
            if text_server is None:
                return http.HttpResponseBadRequest('图片验证码已过期')
            #比对
            if text_server.decode().lower() != text_client.lower() :
                return http.HttpResponseBadRequest('图片验证码不一致')

            #删除图片
            redis_coon.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)
            return http.HttpResponseBadRequest ('数据库连接问题')


        send_flag = redis_coon.get('send_flag_%s'%mobile)
        if send_flag is not None:
            return http.HttpResponseBadRequest('操作太频繁了')

        from random import randint

        sms_code ='%06d' % randint(0, 999999)

        logger.info(sms_code)

        pl = redis_coon.pipeline()

        pl.setex('sms_%s' % mobile, SMS_CODE_EXPIRE_TIME, sms_code)

        pl.setex('send_flag_%s'%mobile,60,1)

        pl.execute()







        # CCP().send_template_sms(mobile,[sms_code,YUNTONGXUN_EXPIRE_TIME],1)
        from celery_tasks.sms.tasks import send_sms_code

        send_sms_code.delay(mobile,sms_code)


        return http.JsonResponse({'code':RETCODE.OK})

# Create your views here.
